package com.aries.ui.widget.demo.module.title;

import com.aries.ui.view.tab.IndicatorStyle;
import com.aries.ui.view.tab.SlidingTabLayout;
import com.aries.ui.view.tab.TextBold;
import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.demo.ResourceTable;
import com.aries.ui.widget.demo.manager.GlideManager;
import com.aries.ui.widget.demo.manager.TabLayoutManager;
import com.aries.ui.widget.demo.module.TabFraction;
import com.aries.ui.widget.demo.util.SizeUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.render.Canvas;
import ohos.agp.render.LinearShader;
import ohos.agp.render.Paint;
import ohos.agp.render.Shader;
import ohos.agp.utils.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.Resource;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: AriesHoo on 2019/4/11 15:08
 * @E-Mail: AriesHoo@126.com
 * @Function: Title 自定义左边、中间、右边View
 * @Description:
 */
public class TitleActionAbility extends AbilitySlice {

    private TitleBarView titleBar;
    private TitleBarView mTitleSearch;
    private TitleBarView mTitleQQ;
    private TitleBarView mTitleWeChat;
    private TitleBarView mTitleLoading;
    private TitleBarView mTitleTab;
    private PageSlider mVpContent;

    private List<Fraction> mListFragment = new ArrayList<>();
    private List<String> mListTitle = new ArrayList<>();
    private Component mViewSearch;
    private Component mViewQq;
    private Image mIvQq;
    private Image mProgressBar;
    private SlidingTabLayout mSlidingTabLayout;
    private AnimatorValue animator;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        //防止布局复用导致重复加载
        ComponentContainer parse = (ComponentContainer) LayoutScatter.getInstance(getContext()).parse(
                ResourceTable.Layout_ability_title_action, null, false);
        setUIContent(parse);

        titleBar = (TitleBarView) findComponentById(ResourceTable.Id_titleBar);
        mTitleSearch = (TitleBarView) findComponentById(ResourceTable.Id_title_searchTitleAction);
        mTitleQQ = (TitleBarView) findComponentById(ResourceTable.Id_title_qqTitleAction);
        mTitleWeChat = (TitleBarView) findComponentById(ResourceTable.Id_title_weChatTitleAction);
        mTitleLoading = (TitleBarView) findComponentById(ResourceTable.Id_title_loadingTitleAction);
        mTitleTab = (TitleBarView) findComponentById(ResourceTable.Id_title_tabTitleAction);
        mVpContent = (PageSlider) findComponentById(ResourceTable.Id_vp_contentTitleAction);

        setTitleBar();
        initView();
    }

    protected void setTitleBar() {
        titleBar.setTitleMainText("TitleBarView 自定义左中右View示例")
                .setTitleSubText("提供部分常用场景,开发者可根据实际场景组合")
                .setTitleSubTextSize(Text.TextSizeType.FP, 12f)
                .setOnLeftTextClickListener(component -> terminate());
    }

    protected void initView() {
        //中间搜索框样式
        mViewSearch = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_search, null, false);
        int parent = ComponentContainer.LayoutConfig.MATCH_PARENT;
        ComponentContainer.LayoutConfig params = new ComponentContainer.LayoutConfig(parent, SizeUtil.dp2px(32));
        params.setMarginRight(SizeUtil.dp2px(4));
        mViewSearch.setLayoutConfig(params);

        mTitleSearch.addCenterAction(new TitleBarView.ViewAction(mViewSearch));
        //QQ TitleBar样式
        mTitleQQ.addDrawTask(this::drawGradientBg, Component.DrawTask.BETWEEN_BACKGROUND_AND_CONTENT); //渐变背景色

        mViewQq = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_qq_header, null, false);

        mTitleQQ.addLeftAction(
                new TitleBarView.ViewAction(mViewQq),
                0,
                new ComponentContainer.LayoutConfig(SizeUtil.dp2px(40), SizeUtil.dp2px(40))
        );

        mIvQq = (Image) mViewQq.findComponentById(ResourceTable.Id_iv_headQQ);
        GlideManager.loadCircleImg("https://picsum.photos/600", mIvQq);

        //微信TitleBar样式
        mTitleWeChat
                .setOnRightTextClickListener(component -> showToast("打开操作菜单"))
                .setActionPadding(0)
                .addRightAction(
                        mTitleWeChat.new ImageAction(ResourceTable.Media_ic_search_normal,
                                component -> showToast("打开搜索页")),
                        0,
                        new ComponentContainer.LayoutConfig(SizeUtil.dp2px(24), SizeUtil.dp2px(24)));

        //中间loading效果
        loading();
        //滑动tabs
        slidingTabs();
    }

    private void slidingTabs() {
        mSlidingTabLayout = new SlidingTabLayout(getContext());
        mTitleTab.addCenterAction(new TitleBarView.ViewAction(mSlidingTabLayout),
                new ComponentContainer.LayoutConfig(
                        ComponentContainer.LayoutConfig.MATCH_CONTENT,
                        ComponentContainer.LayoutConfig.MATCH_PARENT));
        setTab(mSlidingTabLayout);
        mSlidingTabLayout.getDelegate()
                .setIndicatorColor(Color.getIntColor(getContext().getString(ResourceTable.Color_colorTextBlack)))
                .setIndicatorGravity(LayoutAlignment.BOTTOM)
                .setIndicatorHeight(3f)
                .setIndicatorStyle(IndicatorStyle.NORMAL)
                .setIndicatorWidthEqualTitle(false)
                .setTabPadding(SizeUtil.dp2px(6))
                .setTextBold(TextBold.SELECT)
                .setTextSelectColor(Color.getIntColor(getContext().getString(ResourceTable.Color_colorTextBlack)))
                .setTextUnSelectColor(Color.getIntColor("#99333333"))
                .setTextSelectSize(Text.TextSizeType.VP, 18f)
                .setTextSize(Text.TextSizeType.VP, 16f);
        //修改外层Component的宽度，否则会导致滑不动
        getUITaskDispatcher().delayDispatch(() -> {
            ComponentContainer.LayoutConfig layoutConfig = mSlidingTabLayout.getLayoutConfig();
            layoutConfig.width = mSlidingTabLayout.getContainer().getWidth();
            mSlidingTabLayout.setLayoutConfig(layoutConfig);
        }, 1);
    }

    private void setTab(SlidingTabLayout slidingTabLayout) {
        for (int i = 0; i < 20; i++) {
            mListFragment.add(TabFraction.newInstance());
            mListTitle.add("Tab" + i);
        }
        TabLayoutManager.getInstance().setSlidingTabData(
                ((FractionAbility) this.getAbility()), slidingTabLayout, mVpContent, mListTitle, mListFragment);
        slidingTabLayout.setCurrentTab(0);
    }

    private void drawGradientBg(Component component, Canvas canvas) {
        //系统暂不支持带过渡颜色的渐变
        Point[] points = {
                new Point(0, component.getHeight()),
//                    new Point(component.getWidth() * 0.7f, component.getHeight()),
                new Point(component.getWidth(), component.getHeight())
        };
        Color[] colors = {
                new Color(Color.getIntColor("#4e8cfc")),
//                    new Color(Color.getIntColor("#34b0fc")),
                new Color(Color.getIntColor("#33bafc"))
        };
        LinearShader shader = new LinearShader(points, null, colors, Shader.TileMode.CLAMP_TILEMODE);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL_STYLE);
        paint.setShader(shader, Paint.ShaderType.LINEAR_SHADER);
        canvas.drawRect(new Rect(0, 0,
                component.getWidth(), component.getHeight()), paint);
    }

    private void loading() {
        try {
            mProgressBar = new Image(getContext());
            Resource resource = getResourceManager().getResource(ResourceTable.Media_img_loading_wei_bo);
            PixelMapElement element = new PixelMapElement(resource);
            element.setBounds(0, 0, SizeUtil.dp2px(20), SizeUtil.dp2px(20));
            mProgressBar.setImageElement(element);

            ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig(SizeUtil.dp2px(20), SizeUtil.dp2px(20));
            config.setMarginRight(SizeUtil.dp2px(10));

            mTitleLoading.setActionPadding(0);
            mTitleLoading.addCenterAction(new TitleBarView.ViewAction(mProgressBar), 0, config);

            animator = new AnimatorValue();
            animator.setDuration(1000);
            animator.setLoopedCount(Animator.INFINITE);
            animator.setValueUpdateListener((animatorValue, v) -> {
                if(mProgressBar != null)
                    mProgressBar.setRotation(v * 360);
            });
            animator.start();
        } catch (Exception e) {
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mListFragment != null) {
            mListFragment.clear();
        }
        if (mListTitle != null) {
            mListTitle.clear();
        }
        animator.stop();
        animator = null;

        titleBar = null;
        mViewSearch = null;
        mTitleSearch = null;
        mViewQq = null;
        mTitleQQ = null;
        mTitleWeChat = null;
        mTitleLoading = null;
        mTitleTab = null;
        mVpContent = null;
        mListFragment = null;
        mListTitle = null;
        mIvQq = null;
        mProgressBar = null;
        mSlidingTabLayout = null;
    }

    private void showToast(String msg) {
        ToastDialog toastDialog = new ToastDialog(getContext());
        toastDialog.setAlignment(TextAlignment.CENTER)
                .setAutoClosable(true)
                .setDuration(1000)
                .setText(msg)
                .show();
    }
}
